package com.iap.admin.mediator
{
	import com.iap.admin.event.AdminHomeEvent;
	import com.iap.admin.event.AdminMenuEvent;
	import com.iap.admin.model.SampleGridModel;
	import com.iap.admin.view.AdminMenuView;
	import com.iap.admin.view.SampleView;
	import com.iap.admin.view.sample.SampleEditView;
	import com.iap.app.AppGlobal;
	import com.iap.app.util.GlideTransitionEffect;
	import com.iap.common.event.SampleEvent;
	import com.iap.common.mediator.BaseMediator;
	import com.iap.common.model.Sample;
	import com.iap.common.signal.SampleRequestSignal;
	
	import flash.events.Event;
	
	import mx.collections.ArrayList;
	import mx.core.UIComponent;
	
	import org.robotlegs.mvcs.Mediator;
	
	import spark.components.Group;
	import spark.events.ElementExistenceEvent;
	import spark.events.GridEvent;
	
	public class SampleMediator extends BaseMediator
	{
		[Inject]
		public var view:SampleView;
		[Inject]
		public var request:SampleRequestSignal;

		override public function onRegister():void
		{
			view.onOptionClick.add(onClick);
			addContextListener(SampleEvent.RESPONSE, responseHandler);
			addViewListener(GridEvent.GRID_CLICK, gridClickEvent);
			dispatchRequest();
		}
		
		private function gridClickEvent(evt:GridEvent):void
		{ 
			var item:SampleGridModel = evt.item as SampleGridModel;
			if(item==null) return;
			edit(item.sample);
		}
		
		private function dispatchRequest():void
		{
			AppGlobal.startWait();
			request.dispatch(new Sample(), SampleRequestSignal.GET);
		}
		
		private function responseHandler(evt:SampleEvent):void
		{
			AppGlobal.endWait();

			if(evt.response.task == SampleRequestSignal.SAVE)
			{
				edit(evt.response.result as Sample);
			} else {
				view.sampleGrid.dataProvider = setSampleGridData(evt.response.result as Array);
			}
		}
		
		private function setSampleGridData(list:Array):ArrayList
		{
			var result:ArrayList = new ArrayList();
			for(var i:uint = 0; i<list.length; i++)
			{
				var model:SampleGridModel = new SampleGridModel();
				model.order = (i+1);
				model.sample = list[i];
				result.addItem(model);
			}
			return result;
		}

		private function onClick(itemName:String):void
		{
			switch(itemName)
			{
				case SampleView.HOME_NAME:
				{
					optionHome();
					break;
				}
				case SampleView.CREATE_NAME:
				{
					create();
					break;
				}
			}
		}

		private function optionHome():void
		{
			setView(view.parent as Group, new AdminMenuView(), FX_GLIDE_OUT);
		}

		private function create():void
		{
			var empty:Sample = new Sample();
			empty.name = "";
			empty.sampleFillers = [];
			request.dispatch(empty, SampleRequestSignal.SAVE);
		}

		private function edit(item:Sample):void
		{
			var newView:SampleEditView = new SampleEditView();
			newView.onReady.addOnce(function(str:String):void{
				newView.fill(item);
			});
			setView(view.parent as Group, newView);
		}
	}
}